package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.ResultComparator;
import cc.eddic.pratice.programmingparadigms.ResultPredicate;
import cc.eddic.pratice.programmingparadigms.emp02list.ResultList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Comparator;

public class ResultListGcsImpl implements ResultList {

    private static final Logger log = LoggerFactory.getLogger(ResultListGcsImpl.class);

    private Result[] results;

    private int index;

    public ResultListGcsImpl(int capacity) {
        results = new Result[capacity];
        index = 0;
    }

    public ResultListGcsImpl() {
        this(10);
    }

    public ResultListGcsImpl(Result[] results) {
        this(results.length * 2);
        // TODO:
    }

    public ResultListGcsImpl(ResultList results) {
        this(results.size() * 2);
        // TODO:
    }

    @Override
    public void add(Result result) {
        if (log.isDebugEnabled()) log.debug("{} {}", result.getKey(), result.getCount());
        results[index] = result;
        index++;
    }

    @Override
    public Result get(int index) {
        if (index < 0 || index >= size()) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
        }
        return results[index];
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public Result findByGender(String gender) {
        return null;
    }

    @Override
    public Result findByDepartment(String department) {
        return null;
    }

    @Override
    public Result findByJobTitle(String jobTitle) {
        return null;
    }

    public void sort(ResultComparator comparator) {
        // 冒泡排序
        for (int i = 0; i < size(); i++) {
            for (int j = 0; j < size() - i - 1; j++) {
                // 什么情况下要交换
                if (comparator.compare(results[j], results[j + 1]) > 0) {
                    // 交换
                    Result temp = results[j];
                    results[j] = results[j + 1];
                    results[j + 1] = temp;
                }
            }
        }
    }

    @Override
    public Result[] toArray() {
        Result[] r = new Result[size()];
        for (int i = 0; i < size(); i++) {
            r[i] = get(i);
        }
        return r;
    }
}
